// 全局变量
let currentAnalysis = null;
let charts = {};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeUploadArea();
    loadRules();
});

// 初始化上传区域
function initializeUploadArea() {
    const uploadArea = document.getElementById('uploadArea');
    const fileInput = document.getElementById('fileInput');

    // 拖拽上传
    uploadArea.addEventListener('dragover', function(e) {
        e.preventDefault();
        uploadArea.classList.add('dragover');
    });

    uploadArea.addEventListener('dragleave', function(e) {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
    });

    uploadArea.addEventListener('drop', function(e) {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            handleFileUpload(files[0]);
        }
    });

    // 文件选择
    fileInput.addEventListener('change', function(e) {
        if (e.target.files.length > 0) {
            handleFileUpload(e.target.files[0]);
        }
    });
}

// 处理文件上传
function handleFileUpload(file) {
    if (!file.name.endsWith('.tar.gz')) {
        alert('请选择 .tar.gz 格式的文件');
        return;
    }

    const formData = new FormData();
    formData.append('file', file);

    showLoading(true);

    fetch('/upload', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        showLoading(false);
        if (data.error) {
            alert('上传失败: ' + data.error);
        } else {
            loadAnalysis();
        }
    })
    .catch(error => {
        showLoading(false);
        alert('上传失败: ' + error.message);
    });
}

// 显示/隐藏加载状态
function showLoading(show) {
    const loading = document.getElementById('loading');
    if (show) {
        loading.classList.add('show');
    } else {
        loading.classList.remove('show');
    }
}

// 加载分析结果
function loadAnalysis() {
    fetch('/analysis')
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert('加载分析结果失败: ' + data.error);
        } else {
            currentAnalysis = data;
            displayAnalysis(data);
        }
    })
    .catch(error => {
        alert('加载分析结果失败: ' + error.message);
    });
}

// 显示分析结果
function displayAnalysis(data) {
    document.getElementById('analysisResults').style.display = 'block';
    
    // 更新统计卡片
    document.getElementById('totalLogs').textContent = data.total_logs;
    document.getElementById('uniqueComponents').textContent = data.unique_components;
    document.getElementById('duplicateRatio').textContent = data.duplicate_ratio + '%';
    document.getElementById('errorCount').textContent = data.most_frequent_errors.length;

    // 加载各个标签页的数据
    loadOverview(data);
    loadComponents();
    loadDuplicates();
    loadErrors();
    loadTimeline(data);
}

// 加载概览数据
function loadOverview(data) {
    // 最活跃的组件
    const activeComponentsDiv = document.getElementById('activeComponents');
    activeComponentsDiv.innerHTML = '';
    
    data.most_active_components.forEach(([component, stats]) => {
        const div = document.createElement('div');
        div.className = 'd-flex justify-content-between align-items-center mb-2';
        div.innerHTML = `
            <span>${component}</span>
            <span class="badge bg-primary">${stats.count}</span>
        `;
        activeComponentsDiv.appendChild(div);
    });

    // 错误类型分布图
    createErrorChart(data.most_frequent_errors);
}

// 加载组件分析
function loadComponents() {
    fetch('/components')
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            console.error('加载组件数据失败:', data.error);
            return;
        }
        
        createComponentChart(data);
        displayComponentTable(data);
    })
    .catch(error => {
        console.error('加载组件数据失败:', error);
    });
}

// 加载重复日志
function loadDuplicates() {
    fetch('/duplicates')
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            console.error('加载重复日志失败:', data.error);
            return;
        }
        
        displayDuplicates(data);
    })
    .catch(error => {
        console.error('加载重复日志失败:', error);
    });
}

// 加载错误分类
function loadErrors() {
    fetch('/errors')
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            console.error('加载错误分类失败:', data.error);
            return;
        }
        
        createErrorTypeChart(data);
        displayErrorDetails(data);
    })
    .catch(error => {
        console.error('加载错误分类失败:', error);
    });
}

// 加载时间分析
function loadTimeline(data) {
    const timePatterns = data.time_patterns;
    
    // 小时分布图
    createHourlyChart(timePatterns.hourly_distribution);
    
    // 日期分布图
    createDailyChart(timePatterns.daily_distribution);
}

// 创建错误分布图
function createErrorChart(errorData) {
    const ctx = document.getElementById('errorChart');
    if (charts.errorChart) {
        charts.errorChart.destroy();
    }
    
    const labels = errorData.map(([category, logs]) => category);
    const data = errorData.map(([category, logs]) => logs.length);
    
    charts.errorChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: labels,
            datasets: [{
                data: data,
                backgroundColor: [
                    '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF'
                ]
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
}

// 创建组件分布图
function createComponentChart(componentData) {
    const ctx = document.getElementById('componentChart');
    if (charts.componentChart) {
        charts.componentChart.destroy();
    }
    
    const categories = {};
    Object.values(componentData).forEach(component => {
        const category = component.category;
        if (!categories[category]) {
            categories[category] = 0;
        }
        categories[category] += component.count;
    });
    
    const labels = Object.keys(categories);
    const data = Object.values(categories);
    
    charts.componentChart = new Chart(ctx, {
        type: 'pie',
        data: {
            labels: labels,
            datasets: [{
                data: data,
                backgroundColor: [
                    '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF'
                ]
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
}

// 显示组件表格
function displayComponentTable(componentData) {
    const tbody = document.getElementById('componentTableBody');
    tbody.innerHTML = '';
    
    Object.entries(componentData).forEach(([component, stats]) => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${component}</td>
            <td><span class="badge bg-secondary">${stats.category}</span></td>
            <td>${stats.count}</td>
            <td>${Object.entries(stats.levels).map(([level, count]) => 
                `<span class="badge bg-${getLevelColor(level)}">${level}: ${count}</span>`
            ).join(' ')}</td>
        `;
        tbody.appendChild(row);
    });
}

// 显示重复日志
function displayDuplicates(duplicateData) {
    const container = document.getElementById('duplicateList');
    container.innerHTML = '';
    
    Object.entries(duplicateData).forEach(([location, data]) => {
        const card = document.createElement('div');
        card.className = 'card mb-3';
        card.innerHTML = `
            <div class="card-header">
                <strong>${location}</strong>
                <span class="badge bg-warning float-end">重复 ${data.count} 次</span>
            </div>
            <div class="card-body">
                <p class="text-muted">${data.message}</p>
                <small class="text-muted">
                    出现时间: ${data.occurrences.map(o => o.datetime).join(', ')}
                </small>
            </div>
        `;
        container.appendChild(card);
    });
}

// 创建错误类型分布图
function createErrorTypeChart(errorData) {
    const ctx = document.getElementById('errorTypeChart');
    if (charts.errorTypeChart) {
        charts.errorTypeChart.destroy();
    }
    
    const labels = Object.keys(errorData);
    const data = Object.values(errorData).map(logs => logs.length);
    
    charts.errorTypeChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: '错误数量',
                data: data,
                backgroundColor: '#FF6384'
            }]
        },
        options: {
            responsive: true,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
}

// 显示错误详情
function displayErrorDetails(errorData) {
    const container = document.getElementById('errorDetails');
    container.innerHTML = '';
    
    Object.entries(errorData).forEach(([category, logs]) => {
        const card = document.createElement('div');
        card.className = 'card mb-3';
        card.innerHTML = `
            <div class="card-header">
                <strong>${category}</strong>
                <span class="badge bg-danger float-end">${logs.length}</span>
            </div>
            <div class="card-body">
                <div class="log-entries">
                    ${logs.slice(0, 5).map(log => `
                        <div class="log-entry">
                            <small class="text-muted">${log.datetime} [${log.component}]</small>
                            <div>${log.message}</div>
                        </div>
                    `).join('')}
                    ${logs.length > 5 ? `<small class="text-muted">还有 ${logs.length - 5} 条日志...</small>` : ''}
                </div>
            </div>
        `;
        container.appendChild(card);
    });
}

// 创建小时分布图
function createHourlyChart(hourlyData) {
    const ctx = document.getElementById('hourlyChart');
    if (charts.hourlyChart) {
        charts.hourlyChart.destroy();
    }
    
    const labels = Array.from({length: 24}, (_, i) => i);
    const data = labels.map(hour => hourlyData[hour] || 0);
    
    charts.hourlyChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: '日志数量',
                data: data,
                borderColor: '#36A2EB',
                backgroundColor: 'rgba(54, 162, 235, 0.1)',
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
}

// 创建日期分布图
function createDailyChart(dailyData) {
    const ctx = document.getElementById('dailyChart');
    if (charts.dailyChart) {
        charts.dailyChart.destroy();
    }
    
    const sortedDates = Object.keys(dailyData).sort();
    const data = sortedDates.map(date => dailyData[date]);
    
    charts.dailyChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: sortedDates,
            datasets: [{
                label: '日志数量',
                data: data,
                backgroundColor: '#4BC0C0'
            }]
        },
        options: {
            responsive: true,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
}

// 获取日志级别颜色
function getLevelColor(level) {
    switch (level.toLowerCase()) {
        case 'error': return 'danger';
        case 'warning': return 'warning';
        case 'info': return 'info';
        default: return 'secondary';
    }
}

// 显示规则配置模态框
function showRulesModal() {
    loadRules();
    const modal = new bootstrap.Modal(document.getElementById('rulesModal'));
    modal.show();
}

// 加载规则配置
function loadRules() {
    fetch('/rules')
    .then(response => response.json())
    .then(data => {
        displayComponentRules(data.component_categories);
        displayErrorRules(data.error_categories);
    })
    .catch(error => {
        console.error('加载规则失败:', error);
    });
}

// 显示组件分类规则
function displayComponentRules(componentCategories) {
    const container = document.getElementById('componentRulesEditor');
    container.innerHTML = `
        <div class="mb-3">
            <button class="btn btn-success btn-sm" onclick="addComponentCategory()">
                <i class="bi bi-plus"></i> 添加分类
            </button>
        </div>
        <div id="componentCategoriesList">
            ${Object.entries(componentCategories).map(([category, components]) => `
                <div class="card mb-3">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <strong>${category}</strong>
                        <button class="btn btn-danger btn-sm" onclick="removeComponentCategory('${category}')">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                    <div class="card-body">
                        <div class="mb-2">
                            <label class="form-label">组件列表:</label>
                            <input type="text" class="form-control" value="${components.join(', ')}" 
                                   onchange="updateComponentList('${category}', this.value)">
                        </div>
                    </div>
                </div>
            `).join('')}
        </div>
    `;
}

// 显示错误分类规则
function displayErrorRules(errorCategories) {
    const container = document.getElementById('errorRulesEditor');
    container.innerHTML = `
        <div class="mb-3">
            <button class="btn btn-success btn-sm" onclick="addErrorCategory()">
                <i class="bi bi-plus"></i> 添加分类
            </button>
        </div>
        <div id="errorCategoriesList">
            ${Object.entries(errorCategories).map(([category, patterns]) => `
                <div class="card mb-3">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <strong>${category}</strong>
                        <button class="btn btn-danger btn-sm" onclick="removeErrorCategory('${category}')">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                    <div class="card-body">
                        <div class="mb-2">
                            <label class="form-label">匹配模式:</label>
                            <textarea class="form-control" rows="3" 
                                      onchange="updateErrorPatterns('${category}', this.value)">${patterns.join('\n')}</textarea>
                        </div>
                    </div>
                </div>
            `).join('')}
        </div>
    `;
}

// 添加组件分类
function addComponentCategory() {
    const categoryName = prompt('请输入新的组件分类名称:');
    if (categoryName) {
        const components = prompt('请输入组件列表（用逗号分隔）:').split(',').map(c => c.trim());
        
        fetch('/rules/component', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                category_name: categoryName,
                components: components
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                alert('添加失败: ' + data.error);
            } else {
                loadRules();
            }
        })
        .catch(error => {
            alert('添加失败: ' + error.message);
        });
    }
}

// 删除组件分类
function removeComponentCategory(categoryName) {
    if (confirm(`确定要删除分类 "${categoryName}" 吗？`)) {
        fetch(`/rules/component/${categoryName}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                alert('删除失败: ' + data.error);
            } else {
                loadRules();
            }
        })
        .catch(error => {
            alert('删除失败: ' + error.message);
        });
    }
}

// 添加错误分类
function addErrorCategory() {
    const categoryName = prompt('请输入新的错误分类名称:');
    if (categoryName) {
        const patterns = prompt('请输入匹配模式（用换行分隔）:').split('\n').map(p => p.trim());
        
        fetch('/rules/error', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                category_name: categoryName,
                patterns: patterns
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                alert('添加失败: ' + data.error);
            } else {
                loadRules();
            }
        })
        .catch(error => {
            alert('添加失败: ' + error.message);
        });
    }
}

// 删除错误分类
function removeErrorCategory(categoryName) {
    if (confirm(`确定要删除分类 "${categoryName}" 吗？`)) {
        fetch(`/rules/error/${categoryName}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                alert('删除失败: ' + data.error);
            } else {
                loadRules();
            }
        })
        .catch(error => {
            alert('删除失败: ' + error.message);
        });
    }
}

// 更新组件列表
function updateComponentList(category, value) {
    const components = value.split(',').map(c => c.trim());
    
    fetch('/rules', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            component_categories: {
                [category]: components
            }
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert('更新失败: ' + data.error);
        }
    })
    .catch(error => {
        alert('更新失败: ' + error.message);
    });
}

// 更新错误模式
function updateErrorPatterns(category, value) {
    const patterns = value.split('\n').map(p => p.trim());
    
    fetch('/rules', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            error_categories: {
                [category]: patterns
            }
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert('更新失败: ' + data.error);
        }
    })
    .catch(error => {
        alert('更新失败: ' + error.message);
    });
}

// 保存规则
function saveRules() {
    // 规则已经在编辑时实时保存，这里只是关闭模态框
    const modal = bootstrap.Modal.getInstance(document.getElementById('rulesModal'));
    modal.hide();
    alert('规则已保存');
}

// 导出数据
function exportData() {
    if (!currentAnalysis) {
        alert('没有可导出的数据');
        return;
    }
    
    const dataStr = JSON.stringify(currentAnalysis, null, 2);
    const dataBlob = new Blob([dataStr], {type: 'application/json'});
    const url = URL.createObjectURL(dataBlob);
    
    const link = document.createElement('a');
    link.href = url;
    link.download = 'log_analysis_' + new Date().toISOString().slice(0, 10) + '.json';
    link.click();
    
    URL.revokeObjectURL(url);
} 